// 引入必要的头文件
#include "student.h"
#include <iostream>
#include <string>
#include <random>
#include <thread>
#include <chrono>
#include <cstring>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>

using namespace std;

// 向服务器发送模拟学生数据
void send_data(const string& host, int port, long grade, int interval_ms) {
    // 创建套接字
    int sock = 0;
    struct sockaddr_in serv_addr;
    
    // 检查套接字创建是否成功
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        cerr << "创建套接字失败" << endl;
        return;
    }

    // 设置服务器地址信息
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);

    // 将主机地址转换为网络地址
    if (inet_pton(AF_INET, host.c_str(), &serv_addr.sin_addr) <= 0) {
        cerr << "无效的地址/不支持的地址" << endl;
        return;
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        cerr << "连接失败" << endl;
        return;
    }

    // 创建随机数生成器和分布
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(0, 100000);

    // 持续发送学生数据
    while (true) {
        student s;
        s.name = "Student" + to_string(dis(gen));
        s.number = dis(gen);
        s.grade = grade;
        s.hobby = {"hobby1", "hobby2", "hobby3"};

        // 构造要发送的数据字符串
        string data = s.name + "," + to_string(s.number) + "," + to_string(s.grade) + "," + s.hobby[0] + "," + s.hobby[1] + "," + s.hobby[2] + "\n";

        // 发送数据到服务器
        send(sock, data.c_str(), data.size(), 0);

        // 等待一段时间后再发送下一批数据
        this_thread::sleep_for(chrono::milliseconds(interval_ms));
    }

    // 关闭套接字
    close(sock);
}

int main() {
    // 创建两个线程分别模拟两个数据源发送数据到不同的端口
    thread t1(send_data, "127.0.0.1", 12345, 2, 5);
    thread t2(send_data, "127.0.0.1", 12346, 3, 10);
    t1.join();
    t2.join();
    return 0;
}
